import Koa from 'koa'
import jwt from 'koa-jwt'
import cors from 'koa2-cors'

import config from '../config'
import middleware from './middleware'
import router from './router'

const app = new Koa()

middleware.onerror(app)

// app.use(middleware.catchError())
app.use(cors({
  origin: (ctx) => {
    if (ctx.request.header.host.split(':')[0] === 'localhost'
    || ctx.request.header.host.split(':')[0] === '127.0.0.1') {
      ctx.set('Access-Control-Allow-Origin', '*')
    } else {
      ctx.set('Access-Control-Allow-Origin', config.server.host)
    }
  },
  credentials: true,
  allowMethods: ['PUT, POST, GET, DELETE, OPTIONS'],
  allowHeaders: ['Origin, X-Requested-With, Content-Type, Accept', 'Authorization']
}))

  .use(middleware.catchRouterError())
  .use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public|\/user\/login|\/assets/] }))

app.use(middleware.parseQuery({
  allowDots: true
}))

app.use(router.routes())
  .use(router.allowedMethods())

module.exports = app
